/**
* @Company 青鸟软通   
* @Title: DubboResultInterceptor.java 
* @Package com.haier.isales.interceptor 
* @author Liu Wenjie   
* @date 2014-11-11 下午8:06:11 
* @version V1.0   
*/ 
package com.jbinfo.qingcaowan.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.bana.common.util.basic.StringUtils;
import org.bana.common.util.exception.ThrowableUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jbinfo.qingcaowan.common.BaseException;
import com.jbinfo.qingcaowan.common.BusinessException;
import com.jbinfo.qingcaowan.common.HOPException;
import com.jbinfo.qingcaowan.common.JSONResult;
import com.jbinfo.qingcaowan.common.ResultCode;


/** 
 * @ClassName: JSONResultInterceptor 
 * @Description: 对json返回值进行统一封装的方法 
 *  
 */
public class JSONResultInterceptor {
	
	private static final Logger LOG = LoggerFactory.getLogger(JSONResultInterceptor.class);
	/** 
	* @Description: 封装接口对应的返回值
	*/ 
	public Object around(ProceedingJoinPoint jp){
		JSONResult dubboResult = new JSONResult();
		// 执行方法
		try {
			Object proceed = jp.proceed();
			dubboResult.setResultBean(proceed);
			dubboResult.setResultCode(ResultCode.SUCCESS);
			LOG.info("==============正常返回===============");
			return dubboResult;
		} catch (Throwable e) {
			//异常编码
			if(e instanceof BusinessException){
				BusinessException be = (BusinessException)e;
				if(be.getExceptionCode() != null && !StringUtils.isBlank(be.getExceptionCode().getErrorCode())){
					dubboResult.setResultCode(be.getExceptionCode().getErrorCode());
				}else{
					dubboResult.setResultCode(ResultCode.BUSINESS_ERROR);
				}
			}else if(e instanceof BaseException){
				BaseException be = (BaseException)e;
				if(be.getExceptionCode() != null && !StringUtils.isBlank(be.getExceptionCode().getErrorCode())){
					dubboResult.setResultCode(be.getExceptionCode().getErrorCode());
				}else{
					dubboResult.setResultCode(ResultCode.SYSTEM_ERROR);
				}
			}else{
				dubboResult.setResultCode(ResultCode.RUNTIME_ERROR);
			}
			//异常信息
			if(e instanceof HOPException){
				HOPException he = (HOPException)e;
				dubboResult.setErrorMessage(he.getHopErrMsg());
			}else{
				dubboResult.setErrorMessage(e.getMessage());
			}
			
			dubboResult.setErrorStackTrack(ThrowableUtil.getStackTrace(e));
			LOG.info("==============异常返回===============");
			return dubboResult;
		} 

	}
	
}
